<template>
  <div class="mid">
    <el-card class="box-card">
      <el-row>
        <el-col :offset="1" :span="4"
          >订单号:
          <div style="font-size: 10px">
            {{ orderNum }}
          </div>
        </el-col>
        <el-col :span="16">
          <el-steps :active="active" align-center>
            <el-step title="待付款" description=""></el-step>
            <el-step title="待发货" description=""></el-step>
            <el-step title="已发货" description=""></el-step>
            <el-step title="交易完成" description=""></el-step>
          </el-steps>
        </el-col>
      </el-row>
    </el-card>
    <el-card
      class="box-card"
      style="margin-top: 20px"
      v-if="
        orderEntity.state != 5 &&
        orderEntity.state != 1 &&
        orderEntity.state != 2
      "
    >
      <el-row>
        <div id="container"></div>
      </el-row>
    </el-card>
    <el-card style="margin-top: 20px" class="box-card">
      <el-row>
        <el-col :span="5">
          <div>收货人信息</div>
          <div class="common-text">收货人：{{ addr.addressName }}</div>
          <div class="common-text">
            收货地址：{{ addr.province }}{{ addr.city }}{{ addr.county
            }}{{ addr.detail }}
          </div>
          <div class="common-text">手机号：{{ addr.addressTel }}</div>
        </el-col>

        <el-col :offset="1" :span="5">
          <div>付款信息</div>
          <div class="common-text">
            支付方式：{{ showPayMethod(orderEntity.paymentId) }}
          </div>
          <div class="common-text">商品总额：{{ orderEntity.totalPrice }}</div>
          <div class="common-text">
            实付金额：{{ orderEntity.actualAmount }}
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="margin-top: 20px" class="box-card">
      <el-row style="margin-bottom: 20px">
        <el-col> 商品信息 </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="productImg" label="商品信息" width="180">
              <template slot-scope="scope">
                <img
                  :src="scope.row.productImg"
                  style="width: 120px; height: 120px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品信息" width="180">
            </el-table-column>
            <el-table-column prop="productPrice" label="单价" width="180">
            </el-table-column>
            <el-table-column prop="buyNum" label="数量"> </el-table-column>
            <el-table-column prop="createTime" label="下单时间">
            </el-table-column>
            <el-table-column prop="" label="实付款">
              <template slot-scope="scope">
                {{ everyTotalPrice(scope.row.buyNum, scope.row.productPrice) }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :offset="18">
          <div>
            应付总额：
            <span style="font-size: 30px; color: red">{{
              orderEntity.actualAmount
            }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-row style="margin-top: 20px">
      <el-col :span="3" :offset="20">
        <el-button icon="el-icon-back" @click="back">返回</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import bus from "../bus/bus";
window._AMapSecurityConfig = {
  securityJsCode: "865f12f9776362a0872f86caf0de381a",
};

export default {
  created() {
    this.orderId = this.$route.query.orderId;
    // console.log(this.orderId);
    this.selOrderDetail();
    console.log(this.orderEntity);
    // if (this.orderEntity.state == 4) {
    // }

    /* ######################### */
    bus.$on("shareUserInput", (val) => {
      this.autoOptions.input = val.inputId;
      this.searchPlaceInput = val.userInput;
    });
    bus.$on("shareHeatMapShow", (val) => {
      this.showHeatOrNot = val;
    });
  },
  data() {
    return {
      a1: "",
      a2: "",
      /* ###################################### */
      logisticsInfoList: [
        { latitude: "31.930225", longitude: "118.827516" },
        //{ latitude: "23.129152403638752", longitude: "113.42775362698366" },
        // { latitude: "30.454012", longitude: "114.42659" },
        //{ latitude: "31.93182", longitude: "118.633415" },
        { latitude: "31.035032", longitude: "121.611504" },
      ],
      map: null,
      autoOptions: {
        input: "",
      },
      searchPlaceInput: "",
      auto: null,
      placeSearch: null,
      district: null,
      polygons: [],
      showHeatOrNot: false,
      heatmap: null,
      heatmapList: null,
      /* ############################# */
      active: 1,
      orderId: "",
      tableData: [],
      orderNum: "",
      orderEntity: {},
      orderDetail: [],
      addr: {},
    };
  },
  methods: {
    selUserAddr(addressId) {
      this.$axios
        .get("api/scss-server/selUserAddr", {
          params: { addressId: addressId },
        })
        .then((response) => {
          // console.log(response.data);
          if (response.data.code == 200) {
            this.addr = response.data.data;
            this.logisticsInfoList[1].latitude = this.addr.latitude;
            this.logisticsInfoList[1].longitude = this.addr.longitude;
            console.log(this.orderEntity.state);
            if (this.orderEntity.state == 4) {
              this.a1 = this.addr.longitude;
              this.a2 = this.addr.latitude;
              this.initMap();
            } else {
              this.a1 = 118.861723;
              this.a2 = 32.11682;
              this.initMap();
            }

            // console.log(this.logisticsInfoList[1].latitude);
            // console.log(this.logisticsInfoList[1].longitude);
          }
        });
    },
    showPayMethod(id) {
      if (id == 1) {
        return "支付宝";
      } else if (id == 2) {
        return "微信";
      }
    },
    back() {
      this.$router.push({ path: "/orderManage" });
    },
    updateOrderStatus(order) {
      this.active = order.state;
      this.orderNum = order.id;
    },
    everyTotalPrice(buyNum, productPrice) {
      return buyNum * productPrice;
    },
    selOrderDetail() {
      this.$axios
        .get("api/scss-server/selOrderDetail", {
          params: { orderId: this.orderId },
        })
        .then((response) => {
          //console.log(response.data);
          if (response.data.code == 200) {
            this.tableData = response.data.data.orderDetails;
            this.updateOrderStatus(response.data.data.order);
            this.orderEntity = response.data.data.order;
            this.orderDetail = response.data.data.orderDetails;
            // console.log(this.orderEntity);
            this.selUserAddr(this.orderDetail[0].addressId);
          }
        });
    },

    /* ########################################### */
    initMap() {
      AMapLoader.load({
        key: "7726b9d9c249186f5a26485f09ddc2c5",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [116.397227, 39.908934], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.HawkEye());
          this.map.addControl(new AMap.MapType());
          this.map.addControl(new AMap.Geolocation());
          this.auto = new AMap.AutoComplete(this.autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          }); //构造地点查询类
          this.auto.on("select", this.select);
          this.map.on("click", (e) => {
            let lat = e.lnglat.lat;
            let lng = e.lnglat.lng;
            this.getLngLatService(lat, lng);
          });
          //添加固定点标记
          let marker1 = new AMap.Marker({
            position: new AMap.LngLat(118.827516, 31.930225), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: "南京",
          });
          //添加点标记
          this.map.add(marker1);

          // 创建 AMap.Icon 实例：
          let icon = new AMap.Icon({
            size: new AMap.Size(32, 32), // 图标尺寸
            image: require("@/assets/hc.png"), // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(32, 32), // 根据所设置的大小拉伸或压缩图片
          });

          let defineMarker2 = new AMap.Marker({
            // position: new AMap.LngLat(119.912165, 31.874567),
            position: new AMap.LngLat(this.a1, this.a2),
            // offset: new AMap.Pixel(-10, -10),
            icon: icon, // 添加 Icon 实例
            title: "definePlace",
            zoom: 13,
          });

          this.map.add(defineMarker2);

          //添加自定义的点标记
          let defineMarker1 = new AMap.Marker({
            position: new AMap.LngLat(121.173667, 31.090525),
            icon: require("@/assets/mar.png"),
            title: "defineMarkerPlace",
          });
          this.map.add(defineMarker1);

          //圆点标记示例
          // let circleMarker1 = new AMap.CircleMarker({
          //   map: this.map,
          //   center: new AMap.LngLat(121.153667, 31.080525),
          //   radius: 20,
          //   fillColor: '#ff00ff'
          // })

          // circleMarker1.setMap(this.map)

          /* 后加########################################### */

          // 加载插件 - AMap.Drivin
          AMap.plugin("AMap.Driving", () => {
            // 插件加载完成后，初始化 Driving 实例
            const driving = new AMap.Driving({
              // 使用上面得到的地图实例，表示，路径是画在我们当前初始化的这个地图上的
              map: this.map,
              // 关闭实时路况信息
              showTraffic: false,
              // 关闭途径点icon
              //hideMarkers: true,
            });

            // 得到 Driving 实例之后，就可以使用 driving.search() 方法，通过起点和终点绘制路径
            // 此处最好不要使用 logisticsInfoList 直接进行地图绘制；
            // 重新声明一个变量，复制一份经纬度数据
            // 有可能我们的经纬度数据是没有的，所以在这块需要进行判断，并且必须 logisticsInfoList.length >= 2（必须要有起点 和 终点坐标）
            setTimeout(() => {
              if (
                this.logisticsInfoList &&
                this.logisticsInfoList.length >= 2
              ) {
                const list = [...this.logisticsInfoList];
                // 取出 起点、终点、途径点
                const start = list.shift();
                const end = list.pop();
                // 剩下的list就是途径点
                // 该函数接收第四个参数
                // 第一个参数：由起点经纬度组成的数组
                // 第二个参数：由终点经纬度组成的数组
                // 第三个参数：配置对象 - 请移步 3.3
                // 第四个参数：函数 - 执行了该函数，就表示路径已经规划完成
                driving.search(
                  [start.longitude, start.latitude],
                  [end.longitude, end.latitude],
                  {
                    waypoints: list.map((item) => [
                      item.longitude,
                      item.latitude,
                    ]),
                  },
                  () => {
                    // 规划完毕
                  }
                );
              }
            }, 1300);
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
      this.drawBounds(e.poi.name);
      this.map.setZoom(16, true, 1);
    },
    // 行政区区域划分
    drawBounds(newValue) {
      //加载行政区划插件
      if (!this.district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 1, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };

        this.map.plugin(["AMap.DistrictSearch"], () => {
          this.district = new AMap.DistrictSearch(opts);
        });
        // this.district = new AMap.DistrictSearch(opts)
      }
      //行政区查询
      this.district.search(newValue, (status, result) => {
        console.log(result);
        if (result != null) {
          this.feedBack("区域搜索成功", "success");
          if (this.polygons != null) {
            this.map.remove(this.polygons); //清除上次结果
            this.polygons = [];
          }
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              var polygon = new AMap.Polygon({
                strokeWeight: 1,
                path: bounds[i],
                fillOpacity: 0.4,
                fillColor: "#80d8ff",
                strokeColor: "#0091ea",
              });
              this.polygons.push(polygon);
            }
          }
          this.map.add(this.polygons);
          this.map.setFitView(this.polygons); //视口自适应
        } else {
          this.feedBack("区域搜索失败", "error");
        }
      });
    },
    feedBack(msg, feedBackType) {
      this.$message({
        showClose: true,
        message: msg,
        type: feedBackType,
      });
    },
    showHeatMap() {
      this.map.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          //map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search("商场", (status, result) => {
          // console.log(result)

          this.getHotChartPos("商场", result);
        });
      });
      this.$notify({
        title: "成功",
        message: "热力图获取成果，但是由于电脑性能，我们仅加载部分数据",
        type: "success",
      });
    },
    getHotChartPos(detail, result) {
      let lengthSize = result.poiList.pageSize;
      const count = result.poiList.count;
      // const lengthPage = count / lengthSize
      if (lengthSize > count) {
        lengthSize = count;
      }
      for (var n = 0; n < lengthSize; n++) {
        // this.map.plugin(['AMap.PlaceSearch'], () => {
        //构造地点查询类
        var realSearch = new AMap.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: n + 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        realSearch.search(detail, (status, result) => {
          // for (var j = 0; j < 50; j++) {
          // this.map.remove(this.map.getAllOverlays('marker'))
          //var centerPoint = [result.poiList.pois[j].location.lng, result.poiList.pois[j].location.lat]
          // console.log(result)
          //热力图
          this.showHatChart(result);
          // }
        });
      }
    },
    showHatChart(result) {
      var info = [];
      for (let i = 0; i < 50; i++) {
        info.push({
          lng: result.poiList.pois[i].location.lng,
          lat: result.poiList.pois[i].location.lat,
          count: 3 * 50 * Math.round(Math.random() * (10 - 2) + 2),
        });
      }

      this.map.plugin(["AMap.HeatMap"], () => {
        //初始化heatmap对象
        this.heatmap = new AMap.HeatMap(this.map, {
          radius: 56, //给定半径
          opacity: [0, 0.5],
          /*,
            gradient:{
                0.5: 'blue',
                0.65: 'rgb(117,211,248)',
                0.7: 'rgb(0, 255, 0)',
                0.9: '#ffea00',
                1.0: 'red'
            }
             */
        });
        //设置数据集
        this.heatmap.setDataSet({
          data: info,
          max: 100,
        });
        this.heatmapList.push(this.heatmap);
        this.heatmap.show();
      });
    },

    //逆向地理编码服务
    getLngLatService(lat, lng) {
      let pos = [lng, lat];
      let lnglat = new AMap.LngLat(lng, lat);
      let geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        city: "全国",
      });

      //1.点击地图任意位置生成一个marker
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        icon: require("@/assets/mar.png"),
      });
      this.map.add(marker);
      let address = "";
      //2.将位置转化为坐标点-->地理信息
      //3.根据地理信息（地址）进行搜索获取详细信息！
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          address = result.regeocode.formattedAddress;
          let res = {
            pos: pos,
            address: address,
          };

          //需求：固定的窗体信息进行展示！
          bus.$emit("shareAddressDetails", res);
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
  },
  mounted() {
    window.vue = this;
    //DOM初始化完成进行地图初始化
    this.initMap();
  },
  watch: {
    searchPlaceInput(newValue) {
      if (newValue != null) {
        console.log(newValue);
        this.placeSearch.search(newValue);
        this.drawBounds(newValue);
        this.map.setZoom(16, true, 1);
      }
    },
    showHeatOrNot(newValue) {
      if (newValue) {
        this.showHeatMap();
      } else {
        this.heatmap.hide();
      }
    },
  },
};
</script>

<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 900px;
  height: 500px;
}
.mid {
  width: 1000px;
  margin: 0 auto;
}
.common-text {
  font-size: 12px;
  margin-top: 10px;
}
</style>
